import {
  ScriptFactory,
  SearchBarController,
  convertNavData,
} from '@ibiz-template/runtime';

/**
 * 搜索栏增强控制器
 * - DODO紧急修复模板BUG
 * @export
 * @class SearchBarExController
 * @extends {SearchBarController}
 */
export class SearchBarExController extends SearchBarController {
  /**
   * 获取搜索栏的过滤参数
   *
   * @return {*}  {IParams}
   * @memberof SearchBarExController
   */
  getFilterParams(): IParams {
    const params: IParams = {};
    // 快速搜索
    if (this.state.query) {
      params.query = this.state.query;
      // 快速搜索高级
      if (
        this.state.advancedQuickSearch &&
        this.state.quickSearchFieldNames.length
      ) {
        params.queryconds = this.state.quickSearchFieldNames.map(
          name => `n_${name}_like`,
        );
      }
    }

    // 快速分组
    if (
      this.state.selectedGroupItem?.data &&
      typeof this.state.selectedGroupItem.data === 'string' &&
      !this.isBackendSearchGroup
    ) {
      let str = this.state.selectedGroupItem.data;
      try {
        const data = JSON.parse(str);
        if (data.theme_model?.searchconds)
          str = JSON.stringify({ searchconds: data.theme_model?.searchconds });
      } catch (error) {
        ibiz.log.error(error);
      } finally {
        const navParams = ScriptFactory.execSingleLine(str) as IData;
        const addParams = convertNavData(navParams, this.params, this.context);
        Object.assign(params, addParams);
      }
    }
    // 搜索过滤器
    const filters = this.calcFilters();
    if (filters) {
      params.searchconds = filters;
    }
    return params;
  }
}
